import sys
import redis
import json
import time
import atexit
import signal

def cleanup():
    print("正在清理Redis连接...")
    try:
        pubsub.close()
        r.close()
    except Exception as e:
        print(f"清理错误: {str(e)}")

# 注册清理函数到程序退出时调用
atexit.register(cleanup)

# 捕获 SIGINT 和 SIGTERM 信号
def handle_signal(signum, frame):
    print(f"接收到信号 {signum}，正在退出...")
    cleanup()
    sys.exit(0)

signal.signal(signal.SIGINT, handle_signal)
signal.signal(signal.SIGTERM, handle_signal)

sys.stdout.reconfigure(encoding='utf-8')

print("Python 插件已启动...")

# 连接到 Redis
r = redis.Redis(host='127.0.0.1', port=6379, db=0)
pubsub = r.pubsub(ignore_subscribe_messages=True)
pubsub.subscribe('py-request')

def process_message(data):
    try:
        command = data['command']
        user_id = data['event']['user_id']
        response = command[::-1]

        r.publish('py-response', json.dumps({
            'user_id': user_id,
            'response': f"反转结果：{response}"
        }))
        print(f"已处理: {command} → {response}")
    except Exception as e:
        print(f"处理错误: {str(e)}")

print("等待指令中...")
try:
    for message in pubsub.listen():
        if message and message['type'] == 'message':
            data = json.loads(message['data'])
            process_message(data)

except redis.ConnectionError:
    print("Redis 连接丢失，尝试重连...")
    time.sleep(5)
    r = redis.Redis(host='127.0.0.1', port=6379, db=0)
    pubsub = r.pubsub(ignore_subscribe_messages=True)
    pubsub.subscribe('py-request')
except Exception as e:
    print(f"运行错误: {str(e)}")
